package com.heima.ai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.ai.mapper.ChatHistoryMapper;
import com.heima.ai.pojo.ChatHistory;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class CustomerServiceController {

    private final ChatClient serviceChatClient;
    private final ChatHistoryMapper chatHistoryMapper;

    /**
     * 客服
     *
     * @param prompt 问题
     * @param chatId 会话id
     * @return 回答
     */
    @RequestMapping(value = "/service", produces = "text/html;charset=utf-8")
    public Flux<String> service(String prompt, String chatId) {
        // 1.保存会话id
        LambdaQueryWrapper<ChatHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatHistory::getType, "service").eq(ChatHistory::getChatId, chatId);
        ChatHistory chatHistory = chatHistoryMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(chatHistory)) {
            ChatHistory newChatHistory = new ChatHistory();
            newChatHistory.setType("service");
            newChatHistory.setChatId(chatId);
            chatHistoryMapper.insert(newChatHistory);
        }

        // 2.请求模型
        return serviceChatClient.prompt()
                .user(prompt)
                .advisors(a -> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                .stream()
                .content();
    }
}